#include "backup-one.h"

bool backupone::backup_one(const QString &source, const QString &destination, QProgressDialog *dialog)//备份函数
{

    //QDir dir(destination);
    //dir.removeRecursively();
    int i = 0;
    QDir dir;
    GetFile get;
    GetMD5 md5;
    int sum = get.getnum1(source, destination);
    if (sum > 0) {
        dialog->setFixedWidth(600);
        dialog->setWindowTitle("backup progress");
        dialog->setWindowModality(Qt::WindowModal);
        dialog->show();
        dialog->setRange(0, sum);
        dialog->setMinimumDuration(0);

    } else if (sum == 0){
        return true;
    }
    QFile file("../BackupAndRestore/log.txt");
    file.open(QIODevice::WriteOnly | QIODevice::Text | QIODevice::Append);
    QFileInfoList fileInfoList = get.getAllFile(source);//获取源文件夹下所有*文件
    QFileInfoList fileInfoList2 = get.getAllFile(destination);
    QList<QString> dirList = get.getDir(source);
    QList<QString> dirList2 = get.getDir(destination);
    file.write(("start to backup " + source + " to " + destination+ '\n').toUtf8());
    /*foreach (QString str, dirList2) {
        QString newpath2 = str.replace(destination, source);
        if (!QDir(newpath2).exists()) {
            QDir(newpath2.replace(source,destination)).removeRecursively();
            QDateTime *datetime=new QDateTime(QDateTime::currentDateTime());
            QString time = datetime->toString("yyyy-MM-dd hh:mm:ss ddd");
            file.write((time + "  delete dir:  " + newpath2 + '\n').toUtf8());
        }
    }
    foreach (QFileInfo info, fileInfoList2) {
        QString temp;
        temp = info.absoluteFilePath().replace(destination, source);
        if (!QFile(temp).exists()) {
            dir.remove(temp.replace(source,destination));
            QDateTime *datetime=new QDateTime(QDateTime::currentDateTime());
            QString time = datetime->toString("yyyy-MM-dd hh:mm:ss ddd");
            file.write((time + "  delete file:  " + temp.replace(source,destination) + '\n').toUtf8());
        }
    }*/

    /*QMutex mutex;
    QWaitCondition sleep;
    mutex.lock();
    sleep.wait(&mutex, 100);
    mutex.unlock();*/
    /*
    QTime time;
    time.start();
    while(time.elapsed() < 1000)             //等待时间流逝5秒钟
        QCoreApplication::processEvents();   //处理事件
    */
    foreach (QString str, dirList) {
        QString newpath = str.replace(source,destination);
        /*if (QDir(newpath).exists()) {
            QDir(newpath).removeRecursively();
        }*/
        if (!dir.exists(newpath)) {
            dir.mkpath(str.replace(source,destination));
            QTime time1;
            time1.start();
            while(time1.elapsed() < 50)             //等待时间流逝5秒钟
                QCoreApplication::processEvents();   //处理事件
            i += 4096;
            dialog->setLabelText(str.replace(source,destination));
            dialog->setValue(i);
            QDateTime *datetime=new QDateTime(QDateTime::currentDateTime());
            QString time = datetime->toString("yyyy-MM-dd hh:mm:ss ddd");
            file.write((time + "  add dir:  " + str.replace(source, destination) + '\n').toUtf8());

        }
    }

    foreach (QFileInfo info, fileInfoList) {

        QString temp;
        QString newpath = info.absoluteFilePath();
        temp = info.absoluteFilePath().replace(source,destination);
        if ((QFile(temp).exists() && QString::compare(md5.getFileMd5(temp),md5.getFileMd5(newpath)))) {
            QFile::remove(temp);
            QDateTime *datetime=new QDateTime(QDateTime::currentDateTime());
            QString time = datetime->toString("yyyy-MM-dd hh:mm:ss ddd");
            file.write((time + "  delete file:  " + temp + '\n').toUtf8());

        }
        if (!QFile(temp).exists()) {
            auto local = new QThread;
            auto worker = new FileCopyer(local);
            QObject::connect(worker, &FileCopyer::finished, [](bool s) {

            });
            QObject::connect(worker, &FileCopyer::copyProgress, [](qint64 copy, qint64 total) {

            });
            QVector<QString> ve1, ve2;
            ve1.append(info.absoluteFilePath()); ve2.append(temp);
            worker->setSourcePaths(ve1) ;
            worker->setDestinationPaths(ve2);
            local->start();
            /*if (QFile::copy(info.absoluteFilePath(), temp)) {*/
            QTime time1;
            time1.start();
            while(time1.elapsed() < 50)             //等待时间流逝5秒钟
                QCoreApplication::processEvents();//处理事件
            i += QFile(newpath).size();
            dialog->setLabelText(temp);
            dialog->setValue(i);
            QDateTime *datetime=new QDateTime(QDateTime::currentDateTime());
            QString time = datetime->toString("yyyy-MM-dd hh:mm:ss ddd");
            file.write((time + "  add file:  " + temp + '\n').toUtf8());
            //}
        }

    }
    foreach (QString str, dirList2) {
        QString newpath2 = str.replace(destination, source);
        if (!QDir(newpath2).exists()) {
            QDir(newpath2.replace(source,destination)).removeRecursively();
            QDateTime *datetime=new QDateTime(QDateTime::currentDateTime());
            QString time = datetime->toString("yyyy-MM-dd hh:mm:ss ddd");
            file.write((time + "  delete dir:  " + newpath2 + '\n').toUtf8());
        }
    }
    foreach (QFileInfo info, fileInfoList2) {
        QString temp;
        temp = info.absoluteFilePath().replace(destination, source);
        if (!QFile(temp).exists()) {
            dir.remove(temp.replace(source,destination));
            QDateTime *datetime=new QDateTime(QDateTime::currentDateTime());
            QString time = datetime->toString("yyyy-MM-dd hh:mm:ss ddd");
            file.write((time + "  delete file:  " + temp.replace(source,destination) + '\n').toUtf8());
        }
    }

    file.write(("finish backuping " + source + " to " + destination+ '\n').toUtf8());
    file.close();
    //QMessageBox::information(NULL, "Tip", "Backup Successfully!", QMessageBox::Yes | QMessageBox::No, QMessageBox::Yes);
    return true;
}
